package org.fall.mvc.controller;

import org.entity.Auth;
import org.entity.Role;
import org.fall.service.AdminService;
import org.fall.service.RoleService;
import org.fall.service.AuthService;
import org.fall.util.ResultEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;

@Controller
public class AssignController {
    @Autowired
    private AdminService adminService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private AuthService authService;
    @RequestMapping(value = "/assign/to/page.html")
    public String toAssignRolePage(
            @RequestParam("adminId") Integer adminId,
            ModelMap modelMap
    ){
        //查询已分配角色
        List<Role> AssignedRoleList = roleService.getAssignedRole(adminId);
//查询未分配的角色
        List<Role> UnAssignedRoleList = roleService.getUnAssignedRole(adminId);
        //存入模型request.setAttribute()
        modelMap.addAttribute("assignedRoleList",AssignedRoleList);
        modelMap.addAttribute("unAssignedRoleList",UnAssignedRoleList);
        return "assign-role";
    }
    @RequestMapping(value = "/assign/do/assign.html")
    public String saveAdminRoleRelationship(
            @RequestParam("adminId") Integer adminId,
            @RequestParam("pageNum") Integer pageNum,
            @RequestParam("keyword") String keyword,
            // 允许roleIdList为空（因为可能已分配的被清空）
            @RequestParam(value = "roleIdList", required = false) List<Integer> roleIdList
    ) {
        // 调用service层方法
        adminService.saveAdminRoleRelationship(adminId, roleIdList);

        //重定向（减少数据库操作）返回信息页
        return "redirect:/admin/page/page.html?pageNum=" + pageNum + "&keyword=" + keyword;
    }
    @ResponseBody
    @RequestMapping("/assign/get/tree.json")
    public ResultEntity<List<Auth>> getAuthTree(){
        List<Auth> authList = authService.queryAuthList();

        return ResultEntity.successWithData(authList);
    }
    // 获得被勾选的auth信息
    @ResponseBody
    @RequestMapping("/assign/get/checked/auth/id.json")
    public ResultEntity<List<Integer>> getAuthByRoleId(Integer roleId){
        List<Integer> authIdList = authService.getAuthByRoleId(roleId);
        return ResultEntity.successWithData(authIdList);
    }
    @ResponseBody
    @RequestMapping("/assign/do/save/role/auth/relationship.json")
    public ResultEntity<String> getRelationship(
            // 用一个map接收前端发来的数据
            @RequestBody Map<String,List<Integer>> map
    ){
        authService.saveRoleAuthRelationship(map);
        return ResultEntity.successWithoutData();
    }
}
